import { getMenuTree, menuTree } from "@/api/vadmin/menu";
import Layout from "@/layout/index";
import ParentView from "@/components/ParentView";
import { Message } from "element-ui";
import { removeToken } from "@/utils/auth";
/**
 * 路由重定向和角色路由完善
 */
const perfectRouter = function (menuTree, result) {
  if (result) {
    let list = forMenu(menuTree, []);
    list.push({
      path: "/",
      redirect: menuTree[0].route_url
    });
    list.push({ path: "*", redirect: "/404", hidden: true });
    result(list);
  }
};

const forMenu = function (menu, list) {
  menu.reduce((pre, cur) => {
    if (cur.children) {
      if (cur.hidden != 2 && cur.menu_type < 3) {
        list.push(
          Object.assign(createRoute(cur), {
            children: []
          })
        );
        forMenu(cur.children, list[list.length - 1].children);
      }
    } else {
      if (cur.hidden != 2 && cur.menu_type < 3) list.push(createRoute(cur));
    }
  }, []);
  return list;
};

const createRoute = function (data) {
  let path = data.route_url;
  let filePath = data.file_path;
  return {
    name: path.split("/")[1],
    path: "/" + path,
    component:
      filePath != "layout/index" && filePath != "ParentView"
        ? resolve => require(["@/views/" + filePath], resolve)
        : filePath == "layout/index"
          ? Layout
          : ParentView,
    meta: { title: data.title, icon: data.icon },
    hidden: data.hidden ? false : true
  };
};

const menu = {
  state: {
    menuTree: [], //菜单树
    menuRouters: [] //菜单路由
  },
  mutations: {
    SET_MENUTREE: (state, data) => {
      state.menuTree = data;
    },
    SET_MENUROUTERS: (state, data) => {
      state.menuRouters = data;
    }
  },
  actions: {
    getMenuTree({ commit, state }, data) {
      return new Promise((resolve, reject) => {
        // menuTree({ key: "RPMS项目管理系统" }).then(res => {
        //   commit("SET_MENUTREE", res.data.List[0].children);
        //   localStorage.setItem(
        //     "menu",
        //     JSON.stringify(res.data.List[0].children)
        //   );
        //   perfectRouter(state.menuTree, routers => {
        //     commit("SET_MENUROUTERS", routers);
        //     resolve(routers);
        //   });
        // });
        // return;
        getMenuTree()
          .then(res => {
            if (res.data == null) {
              Message({
                message: "暂无该项目访问权限，如需要访问请联系管理员",
                type: "error"
              });
              setTimeout(() => {
                removeToken();
                location.href = "/login";
              }, 1500);
              return;
            }
            res.data.sort((a, b) => {
              return a.sort - b.sort;
            });
            commit("SET_MENUTREE", res.data);
            localStorage.setItem("menu", JSON.stringify(res.data));
            // 路由完善
            perfectRouter(state.menuTree, routers => {
              // console.log("set routers", routers);
              commit("SET_MENUROUTERS", routers);
              resolve(routers);
            });
          })
          .catch(error => {
            reject(error);
          });
      });
    }
  }
};

export default menu;
